package com.jl.web;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
public class PageServlet extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer pageItem = Integer.valueOf(req.getParameter("pageItem"));
        Integer currentPage = Integer.valueOf(req.getParameter("currentPage"));
        //加载数据库
        DataSource dataSource = new ComboPooledDataSource();
        QueryRunner queryRunner = new QueryRunner(dataSource);
        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(currentPage);
        try {
            Object[] query = (Object[]) queryRunner.query("select count(*) from users", new ArrayHandler());
            pageBean.setCount((Long) query[0]);
            pageBean.setPageItem(pageItem);
            int pageCount = (int) Math.ceil(pageBean.getCount() * 1.0 / pageBean.getPageItem());
            pageBean.setPageCount(pageCount);
            Object[] pars = {(pageBean.getCurrentPage() - 1) * pageBean.getPageItem(), pageBean.getPageItem()};
            System.out.println(Arrays.toString(pars));
            List<User> users = (List<User>) queryRunner.query("select * from users limit ?,?", pars, new BeanListHandler(User.class));
            pageBean.setUsers(users);
            req.setAttribute("pageBean",pageBean);
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
